package com.mycontract.suitepro

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.webkit.WebView
//import com.facebook.FacebookSdk
//import com.facebook.appevents.AppEventsLogger
import com.mycontract.suitepro.base.BaseActivity
import com.mycontract.suitepro.utils.*
import com.mycontract.suitepro.utils.analytics.util.AnalyticsUtil
//import com.zhi.syc.data.ASBuilder
//import com.zhi.syc.data.ASSycManager
//import com.zhi.syc.point.ASPointBuilder
//import com.zhi.syc.point.ASPointSycManager
import java.util.*


class ProjectApplication : Application() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context

        @SuppressLint("StaticFieldLeak")
        lateinit var instance: ProjectApplication

        var mFrontActivityCount = 0
    }

    override fun onCreate() {
        super.onCreate()
        context = applicationContext
        instance = this

        try {
            //适配android 9webview
            initPieWebView()

            //is login
            UserStateUtil.isContractSuiteDidContractSuiteLogin()

            //as sdk
            initContractSuiteASContractSuiteDeviceContractSuiteLib()

            //life cycle
            initContractSuiteLifeContractSuiteCycleContractSuiteCallback()

            // analytics sdk
            AnalyticsUtil.init(this)


        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun initContractSuiteASContractSuiteDeviceContractSuiteLib() {
//        try {
//            ASBuilder.setMock(false)
//            ASBuilder.setLog(false)
//            ASBuilder.setServerHost(ApiUrl.BASE_URL)
//            ASBuilder.setPathApplist(ApiUrl.CONTRACTSUITE_PATH_APPLIST.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathContactResult(ApiUrl.CONTRACTSUITE_PATH_CONTACT_RESULT.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathContact(ApiUrl.CONTRACTSUITE_PATH_CONTACT.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathMessage(ApiUrl.CONTRACTSUITE_PATH_MESSAGE.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathDevice(ApiUrl.CONTRACTSUITE_PATH_DEVICE.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathImage(ApiUrl.CONTRACTSUITE_PATH_IMAGE.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathBattery(ApiUrl.CONTRACTSUITE_PATH_BATTERY.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathHardware(ApiUrl.CONTRACTSUITE_PATH_HARDWARE.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathStore(ApiUrl.CONTRACTSUITE_PATH_STORE.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathMedia(ApiUrl.CONTRACTSUITE_PATH_MEDIA.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathNetwork(ApiUrl.CONTRACTSUITE_PATH_NETWORK.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathLocation(ApiUrl.CONTRACTSUITE_PATH_LOCATION.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathCalendar(ApiUrl.CONTRACTSUITE_PATH_CALENDAR.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathScanFilePath(ApiUrl.CONTRACTSUITE_PATH_WHATSAPP_DIR.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathSettingAccount(ApiUrl.CONTRACTSUITE_PATH_SETTING_ACCOUNT.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setPathAduid(ApiUrl.CONTRACTSUITE_PATH_ADUID.toContractSuiteCombineContractSuiteUrlContractSuitePath())
//            ASBuilder.setAppid(ProjectConfig.CONTRACTSUITE_Product)
//            ASBuilder.setKeyProduct(ProjectConfig.CONTRACTSUITE_Product)
//            ASSycManager.getInstance().init(this)
//
//            ASPointBuilder.URL_SERVER_HOST = ApiUrl.BASE_URL
//            ASPointBuilder.PATH_POINT_RECORD =
//                ApiUrl.CONTRACTSUITE_PATH_POINT_RECORD.toContractSuiteCombineContractSuiteUrlContractSuitePath()
//            ASPointBuilder.KEY_PRODUCT = ProjectConfig.CONTRACTSUITE_Product
//            ASPointBuilder.KEY_APPID = ProjectConfig.CONTRACTSUITE_Product
//            ASPointBuilder.KEY_VERSION = ProjectConfig.CONTRACTSUITE_Version.toString()
//            ASPointSycManager.getInstance().init(this)
//
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
    }

    private fun initContractSuiteLifeContractSuiteCycleContractSuiteCallback() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
//                TODO("Not yet implemented")
            }

            override fun onActivityStarted(p0: Activity) {
//                TODO("Not yet implemented")
                println("onActivityStarted:${p0::class.java.simpleName}")
                mFrontActivityCount += 1;
            }

            override fun onActivityResumed(p0: Activity) {
//                TODO("Not yet implemented")
            }

            override fun onActivityPaused(p0: Activity) {
//                TODO("Not yet implemented")
            }

            override fun onActivityStopped(p0: Activity) {
//                TODO("Not yet implemented")
                println("onActivityStopped:${p0::class.java.simpleName}")
                mFrontActivityCount -= 1;
                if (mFrontActivityCount == 0) {
                    println("正在切换到后台，当前activity:${p0::class.java.simpleName}")
                    try {
                        if (p0 is BaseActivity) {
                            var gTag = p0.ACTIVITY_CONTRACTSUITE_TAG
                            if (gTag.isNotBlank()) {
                                gTag = "BACKGROUND_$gTag"
                                AnalyticsUtil.saveHitPointInfo(
                                    type = gTag,
                                    remark = System.currentTimeMillis().toString()
                                )
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
//                TODO("Not yet implemented")
            }

            override fun onActivityDestroyed(p0: Activity) {
//                TODO("Not yet implemented")
            }
        })
    }

    //适配android 9网络进程
    private fun initPieWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getProcessName(this)
            if (ProjectConfig.CONTRACTSUITE_Pck != processName) {
                WebView.setDataDirectorySuffix(processName!!)
            }
        }
    }

    private fun getProcessName(context: Context?): String? {
        if (context == null) return null
        val manager: ActivityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        if (manager != null) {
            for (processInfo in manager.runningAppProcesses) {
                if (processInfo.pid == Process.myPid()) {
                    return processInfo.processName
                }
            }
        }
        return getString(R.string.app_name).uppercase(Locale.getDefault())
    }
}